import { useRoutes, useLocation } from 'react-router-dom'
import route from '@/router'
import { useEffect, useState } from 'react'
import Nav from '@/components/nav/nav'
import checkToken from '@/utils/checkToken'
import { useDispatch, useSelector } from 'react-redux'
import { message } from 'antd'
import { getInfo } from '@/api/user'
import { GotoPage } from './utils/gotoPage'

// import { lazy, Suspense } from 'react'
// const Login = lazy(() => import('@/components/login/login'))

function App() {
  /**
   * 变量集合出
   */
  const dispatch = useDispatch() // store
  const [messageApi, contextHolder] = message.useMessage() //消息提示框
  const { token } = useSelector((state: RootState) => state.handleUser)
  const location = useLocation()
  const [isShowNav, setIsShowNav] = useState(false) // 是否展示nav组件
  const gotoPage = new GotoPage()

  /**
   * 判断token是否过期
   */
  useEffect(() => {
    const checkTokenExpiry = async () => {
      const isExpired = checkToken(new Date().getTime(), Number(localStorage.getItem('record-time') || 0))

      if (isExpired) {
        dispatch({ type: 'setToken', val: '' })
        dispatch({ type: 'setUserInfo', val: {} })
        // localStorage.setItem('token', '')
        // localStorage.setItem('record-time', '')
        messageApi.open({
          type: 'warning',
          content: '登陆已过期'
        })
      } else {
        const user = await getInfo()
        dispatch({ type: 'setUserInfo', val: user.data })
      }
    }

    checkTokenExpiry()
  }, [dispatch, messageApi])
  /**
   * const location = useLocation()
   *    location.pathname==="/login"
   *
   * const navigateTo = useNavigate()
   *     navigateTo("/login");
   */
  /**
   * 响应式 rem
   */
  useEffect(() => {
    console.log(process.env.NODE_ENV === 'development' ? '当前是开发环境' : '当前是生成环境')
    function setRem() {
      const baseFontSize = 16
      const viewportWidth = window.innerWidth || document.documentElement.clientWidth

      // 考虑缩放比例，根据你的设备情况进行调整
      // const scaleFactor = 1.5 // 缩放比例
      // const adjustedViewportWidth = viewportWidth / scaleFactor

      const rem = (viewportWidth / 1920) * baseFontSize // 根据设计调整375
      document.documentElement.style.fontSize = rem + 'px'
    }

    // 在初始加载和窗口调整大小时设置rem单位
    setRem()
    window.addEventListener('resize', setRem)

    // 在组件卸载时清除事件监听器
    return () => {
      window.removeEventListener('resize', setRem)
    }
  }, [])

  // 后续可以在这里手写封装路由守卫
  const outlet = useRoutes(route)
  const routerObject = useRoutes(route)
  const routeinfo = routerObject?.props.match.route

  /**
   * 是否展示登陆组件
   */
  useEffect(() => {
    console.log(routeinfo)
    if (routeinfo) {
      if (routeinfo.meta.isPrivate) {
        if (!token) {
          console.log('未登录不可访问', location.pathname.substring(1))
          gotoPage.gotoLogin({ from: location.pathname.substring(1) })
        }
      }

      if (location.pathname === '/login' || location.pathname === '/register') {
        setIsShowNav(true)
      } else {
        setIsShowNav(false)
      }
    }
  }, [location.pathname, routeinfo, token, dispatch])

  return (
    <>
      {contextHolder}
      <div className="App">
        {!isShowNav && <Nav />}
        {/* 样式是驼峰的 */}
        {/* {!isShowNav && <div className="placeholder" style={{ height: '3.125rem' }}></div>} */}
        {/* {isShowLogin && (
        <Suspense fallback="加载中">
          <Login></Login>
        </Suspense>
      )} */}
        <div className="body_content">{outlet}</div>
      </div>
    </>
  )
}

export default App
